package com.college.controller.products;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.college.common.constant.ErrorMsg;
import com.college.common.pojo.ao.Order;
import com.college.common.pojo.vo.ResultVo;
import com.college.common.utils.IdFactoryUtil;
import com.college.common.utils.UserUtils;
import com.college.products.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;

@RestController
@RequestMapping("/order")
@Api(tags = "订单")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "新增订单")
    @PostMapping("/add")
    public ResultVo addOrder(@RequestBody Order order) {
        Long shUserId = UserUtils.getHeaderUserId();
        order.setOrderNumber(IdFactoryUtil.getOrderId());
        order.setCreateTime(new Date());
        order.setUserId(shUserId);
        order.setOrderStatus((byte) 0);
        order.setPaymentStatus((byte) 0);
        if (orderService.addOrder(order)) {
            return ResultVo.success(order);
        }
        return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
    }

    @ApiOperation(value = "获取订单信息")
    @GetMapping("/info")
    public ResultVo getOrderInfo(@RequestParam Long id) {
        Long shUserId = UserUtils.getHeaderUserId();
        Order order = orderService.getOrder(id);
        if (order.getUserId().equals(shUserId) ||
                order.getIdleItem().getUserId().equals(shUserId)) {
            return ResultVo.success(order);
        }
        return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
    }

    @ApiOperation(value = "更新订单信息")
    @PostMapping("/update")
    public ResultVo updateOrder(@RequestBody Order order,
                                @RequestParam(value = "price", required = false) String price) {
        if (ObjectUtils.isNotEmpty(order.getPaymentStatus()) && order.getPaymentStatus().equals((byte) 1)) {
            order.setPaymentTime(new Date());
        }
        if (orderService.updateOrder(order)) {
            return ResultVo.success(order);
        }
        return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
    }

    @ApiOperation(value = "获取当前用户订单")
    @GetMapping("/my")
    public ResultVo getMyOrder() {
        Long shUserId = UserUtils.getHeaderUserId();
        return ResultVo.success(orderService.getMyOrder(shUserId));
    }

    @ApiOperation(value = "获取卖出的闲置的订单信息")
    @GetMapping("/my-sold")
    public ResultVo getMySoldIdle() {
        Long shUserId = UserUtils.getHeaderUserId();
        return ResultVo.success(orderService.getMySoldIdle(shUserId));
    }
}
